package com.github.xzb617.client.flow.core.rules.chain;

import com.github.xzb617.client.flow.cache.CounterCache;
import com.github.xzb617.client.flow.core.FlowContext;
import com.github.xzb617.client.flow.core.FlowException;
import com.github.xzb617.client.flow.core.FlowProperties;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 规则链
 * <p>
 *     组合不同的规则，来实现规则限流器的限流功能
 * </p>
 * @author xzb617
 */
public class RuleChain implements Rule {

    private final List<Rule> rules;
    private final int size;
    private int position;

    public RuleChain(List<Rule> rules) {
        this.rules = rules;
        this.size = rules.size();
        this.position = 0;
    }

    @Override
    public boolean enabled(FlowProperties.RulesProperties config) {
        return false;
    }

    @Override
    public void validate(FlowContext context, FlowProperties.RulesProperties config, CounterCache cache, RuleChain chain) throws FlowException {
        if (this.position != this.size) {
            // 调用规则链中校验方法
            ++ this.position;
            Rule nextRule = this.rules.get(this.position - 1);
            nextRule.validate(context, config, cache,this);
        }
    }

    @Override
    public void validateInternal(FlowContext context, FlowProperties.RulesProperties config, CounterCache cache, RuleChain chain) throws FlowException {
        // nothing to do, so empty
    }
}
